package com.authine.cloudpivot.ext.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.constants.ServiceUrlConst;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeMemberPurchaseOrder;
import com.authine.cloudpivot.ext.dto.kingDee.request.KingDeeMemberPurchaseOrderGood;
import com.authine.cloudpivot.ext.dto.transfer.*;
import com.authine.cloudpivot.ext.enums.order.transfer.*;
import com.authine.cloudpivot.ext.service.TransferOrderService;
import com.authine.cloudpivot.ext.service.TransferPurchaseVoucherService;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.gateway.bo.BOValidatedAndFormatService;
import com.authine.mvp.app.launcher.utils.Json;
import com.authine.mvp.app.launcher.utils.JsonParseObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
public class TransferOrderServiceImpl extends ApplicationBaseService implements TransferOrderService {

    private final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);
    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    /**
     * 生成采购订单
     *
     * @param dto 转采订单
     *            cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.save
     * @return
     */
    @Override
    public SingleResponse<BO> submitTransferOrder(MemberPurchaseOrderDto dto) throws RuntimeException {
        SingleResponse<BO> result = null;
        List<String> writeBackTradeOrderGoodsIds = new ArrayList<>();
        if (checkPurchaseOrder(dto)) {
            Map<String, Object> memberPurchaseOrderMap = saveMemberPurchaseGoods(dto);
            List<Map<String, Object>> memberPurchaseOrderGoodsList = (ArrayList) memberPurchaseOrderMap.get("memberPurchaseOrderGoodsList");
            //下单时，未付金额为采购金额，已申请付款金额为0
//            memberPurchaseOrderMap.put("no_payment_amount", dto.getNo_payment_amount());
//            memberPurchaseOrderMap.put("payment_amount", 0.0);
            result = BoServiceUtils.createBo(ModelConst.T_MEMBER_PURCHASE_ORDER, Collections.singletonList(memberPurchaseOrderMap));
            for (Map<String, Object> objectMap : memberPurchaseOrderGoodsList) {
                objectMap.put("member_purchase_order_id", result.getData().getBizObjectId());
            }
            BoServiceUtils.createBo(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, memberPurchaseOrderGoodsList);
            if (!CollectionUtils.isEmpty(result.getData().getData())) {
                //成功以后返回的id用于修改p单号
                String poCode = StringUtils.addZeroForNum(result.getData().getBizObjectId(), 6);
                poCode = "P" + poCode;
                JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).putFieldAndVal("po_code", poCode).eq("id", result.getData().getBizObjectId()).update();
            }
            for (MemberPurchaseOrderGoodsDto memberPurchaseOrderGoods : dto.getMemberPurchaseOrderGoods()) {
                Map<String, Object> transferOrderGoods = selectModelById(memberPurchaseOrderGoods.getTransfer_order_goods_id(), ModelConst.T_TRANSFER_ORDER_GOODS);
                if (null != transferOrderGoods) {
                    Map<String, Object> transferOrderGoodsParam = new HashMap<>();
                    //更新为已采 已采购数量
                    transferOrderGoodsParam.put("id", transferOrderGoods.get("id"));
                    transferOrderGoodsParam.put("not_purchase", true);
                    transferOrderGoodsParam.put("quantity_purchased", BigDecimalUtils.add(memberPurchaseOrderGoods.getNum(), BigDecimalUtils.isNull(transferOrderGoods.get("quantity_purchased"))));
                    transferOrderGoodsParam.put("purchase_batch", BigDecimalUtils.add(BigDecimalUtils.isNull(transferOrderGoods.get("purchase_batch")), BigDecimal.ONE).intValue());
                    SingleResponse<BO> tansResult = BoServiceUtils.updateMainBo(ModelConst.T_TRANSFER_ORDER_GOODS, transferOrderGoodsParam);
                    //打上转采标识
                    writeBackTradeOrderGoodsIds.add((String) tansResult.getData().getData().get("cloud_order_goods_id"));
                }
            }
        }
        //转采回写，直接赋值给true
        if (!CollectionUtils.isEmpty(writeBackTradeOrderGoodsIds)) {
            //根据平台订单商品id,查询对应的交易记录t_trade,t_trade.transferPurchase=true,打上转采标识
            try {
                String url = HttpClients.getUrl(AppConst.FINANCIALCENTER, ServiceUrlConst.WRITE_BACK_TRANSFER_URL);
                log.info("回写交易转采标识 param:"+ JSON.toJSONString(writeBackTradeOrderGoodsIds));
                String writeBackResult = HttpClients.execute(url, Collections.singletonList(writeBackTradeOrderGoodsIds));
                log.info("回写交易转采标识 result:"+ writeBackResult);
            } catch (Exception e) {
                log.error("回写交易转采标识 错误信息:"+ e);
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 验证采购订单及商品
     */
    private boolean checkPurchaseOrder(MemberPurchaseOrderDto memberPurchaseOrder) throws RuntimeException {
        boolean checkOk = false;
        if (null != memberPurchaseOrder) {
//            if (!RegexUtils.notNull(memberPurchaseOrder.getTransferOrderIds())) {
//                throw new RuntimeException("销售单号为空'");
//            }
            if (null == memberPurchaseOrder.getPayment_id()) {
                throw new RuntimeException("付款方式为空");
            }

            if (null == memberPurchaseOrder.getVendor_id()) {
                throw new RuntimeException("供应商为空");
            }
            if (null == memberPurchaseOrder.getInvoice_rate() || !RegexUtils.check(RegexUtils.Type.IS_NUMBER, memberPurchaseOrder.getInvoice_rate().toString())) {
                throw new RuntimeException("请选择正确税率");
            }
            if (null != memberPurchaseOrder.getInvoice_type() && memberPurchaseOrder.getInvoice_type().equals(InvoiceApplyTypeEnum.VAT_ORDINARY.getId()) && memberPurchaseOrder.getInvoice_rate().compareTo(BigDecimal.ZERO) != 0) {
                throw new RuntimeException("增值税普通发票税率必须为0");
            }
            if (null == memberPurchaseOrder.getRequested_date()) {
                throw new RuntimeException("需求日期为空");
            }
            if (null == memberPurchaseOrder.getSale_amount()) {
                throw new RuntimeException("销售总价为空");
            }
            if (null == memberPurchaseOrder.getPurchase_amount()) {
                throw new RuntimeException("采购总价为空");
            }
            checkOk = true;

            if (checkOk) {
                //校验采购商品
                if (null != memberPurchaseOrder.getMemberPurchaseOrderGoods()) {
                    for (MemberPurchaseOrderGoodsDto memberPurchaseOrderGood : memberPurchaseOrder.getMemberPurchaseOrderGoods()) {
                        //查询转采订单商品
                        if (StringUtils.isBlank(memberPurchaseOrderGood.getTransfer_order_goods_id())) {
                            throw new RuntimeException("转采订单商品Id为空");
                        }
                        Map<String, Object> transferOrderGoods = selectModelById(memberPurchaseOrderGood.getTransfer_order_goods_id(), ModelConst.T_TRANSFER_ORDER_GOODS);
                        if (null == memberPurchaseOrderGood.getPrice() || memberPurchaseOrderGood.getPrice().compareTo(BigDecimal.ZERO) <= -1) {
                            throw new RuntimeException("采购单价为空");
                        }
                        if (null == memberPurchaseOrderGood.getNum()) {
                            throw new RuntimeException("采购数量为空");

                        }
                        if (memberPurchaseOrderGood.getNum().compareTo(BigDecimal.ZERO) <= 0) {
                            throw new RuntimeException("采购数量不能小于0");
                        }
                        //采购数量不能大于销售数量
                        if (BigDecimalUtils.sub(BigDecimalUtils.isNull(transferOrderGoods.get("num")), getRefundedNum((String) transferOrderGoods.get("cloud_order_goods_id"), null)).compareTo(memberPurchaseOrderGood.getNum()) > 1) {
                            throw new RuntimeException("转采订单商品:" + memberPurchaseOrderGood.getTransfer_order_goods_id() + "采购数量不能大于销售数量");
                        }
                        if (memberPurchaseOrderGood.getNum().compareTo(BigDecimal.ZERO) <= 0) {
                            throw new RuntimeException("采购数量不能小于0");
                        }
                        if (null == memberPurchaseOrderGood.getGross_profit_rate()) {
                            throw new RuntimeException("采购毛利为空");
                        }
                        if (null == memberPurchaseOrderGood.getDelivery_time()) {
                            throw new RuntimeException("交货日期为空");
                        }
                        if (null == memberPurchaseOrderGood.getAmount()) {
                            throw new RuntimeException("采购商品合计为空");

                        }
                        checkOk = true;
                    }
                } else {
                    throw new RuntimeException("操作失败:采购商品的必填项需要填写");
                }
            }
        } else {
            throw new RuntimeException("操作失败:采购单必填项需要填写");
        }
        return checkOk;
    }

    /**
     * 保存采购订单商品
     *
     * @param memberPurchaseOrder
     * @return
     * @throws RuntimeException
     */
    private Map<String, Object> saveMemberPurchaseGoods(MemberPurchaseOrderDto memberPurchaseOrder) throws RuntimeException {
        Map<String, Object> memberPurchaseOrderMap = BeanUtil.beanToMap(memberPurchaseOrder);
        //采购员
        String buyerName = null;
        if (StringUtils.isNotBlank(memberPurchaseOrder.getBuyer_id())) {
            memberPurchaseOrderMap.put("buyer_id", memberPurchaseOrder.getBuyer_id());
            Map<String, Object> buyer = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_PURCHASING_AGENT).selectField("*")
                    .eq("id", memberPurchaseOrder.getBuyer_id()).queryForMap();
            buyerName = CollectionUtils.isEmpty(buyer)? null:(String) buyer.get("name");
            memberPurchaseOrderMap.put("buyer", buyerName);
        }
        //采购供应商
        String vendorName = null;
        if (StringUtils.isNotBlank(memberPurchaseOrder.getVendor_id())) {
            memberPurchaseOrderMap.put("vendor_id", memberPurchaseOrder.getVendor_id());
            Map<String, Object> transferVendor = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_TRANSFER_VENDOR).selectField("*")
                    .eq("id", memberPurchaseOrder.getVendor_id()).queryForMap();
            vendorName = CollectionUtils.isEmpty(transferVendor)? null:(String) transferVendor.get("company_name");
            memberPurchaseOrderMap.put("vendor_name", vendorName);
        }
        if (null != memberPurchaseOrder.getNo_payment_amount()) {
            memberPurchaseOrderMap.put("no_payment_amount", memberPurchaseOrder.getPurchase_amount());
        }
        if (null != memberPurchaseOrder.getPay_account_id()) {
            memberPurchaseOrderMap.put("pay_account_id", memberPurchaseOrder.getPay_account_id());
        }
        memberPurchaseOrderMap.put("invoice_type", memberPurchaseOrder.getInvoice_type());
        memberPurchaseOrderMap.put("pre_sale_amount", memberPurchaseOrder.getPre_sale_amount());
        memberPurchaseOrderMap.put("customer_name", Objects.isNull(memberPurchaseOrder.getCustomer_name())?null:StringUtils.repeatString(memberPurchaseOrder.getCustomer_name(), ","));
        memberPurchaseOrderMap.put("invoice_status", PurchaseInvoiceEnum.NEW.id);
        memberPurchaseOrderMap.put("platform_name", memberPurchaseOrder.getPlatform_name());
        memberPurchaseOrderMap.put("is_rp", false);
        memberPurchaseOrderMap.put("contract_or_sent", false);
        memberPurchaseOrderMap.put("invoice_price", BigDecimal.ZERO);

        List<Map<String, Object>> saveMemberPurchaseGoods = new ArrayList<>();
        BigDecimal purchaseAmount = BigDecimal.ZERO;
        BigDecimal prePurchaseAmount = BigDecimal.ZERO;
        for (MemberPurchaseOrderGoodsDto memberPurchaseOrderGood : memberPurchaseOrder.getMemberPurchaseOrderGoods()) {
            if (memberPurchaseOrderGood.getAmount().compareTo(BigDecimal.ZERO) < 1) {
                throw new RuntimeException("采购总金额不能小于等于0");
            }
            Map<String, Object> newMemberPurchaseOrderGoods = new HashMap<>();
            newMemberPurchaseOrderGoods.put("transfer_order_goods_id", memberPurchaseOrderGood.getTransfer_order_goods_id());
            newMemberPurchaseOrderGoods.put("price", memberPurchaseOrderGood.getPrice());
            newMemberPurchaseOrderGoods.put("pre_price", memberPurchaseOrderGood.getPre_price());
            newMemberPurchaseOrderGoods.put("freight", memberPurchaseOrderGood.getFreight());
            newMemberPurchaseOrderGoods.put("num", memberPurchaseOrderGood.getNum());
            newMemberPurchaseOrderGoods.put("gross_profit_rate", BigDecimalUtils.round(memberPurchaseOrderGood.getGross_profit_rate(), 2));
            newMemberPurchaseOrderGoods.put("amount", memberPurchaseOrderGood.getAmount());
            newMemberPurchaseOrderGoods.put("pretax_amount", memberPurchaseOrderGood.getPretax_amount());
            newMemberPurchaseOrderGoods.put("delivery_time", memberPurchaseOrderGood.getDelivery_time());
            newMemberPurchaseOrderGoods.put("memo", memberPurchaseOrderGood.getMemo());
            newMemberPurchaseOrderGoods.put("purchase_batch", null == memberPurchaseOrderGood.getPurchase_batch() ? 1 : memberPurchaseOrderGood.getPurchase_batch() + 1);
            if (null == memberPurchaseOrderGood.getPurchase_status()) {
                newMemberPurchaseOrderGoods.put("member_purchase_goods_status", MemberPurchaseOrderGoodsEnum.NEW.id.toString());
            }
            if (null == memberPurchaseOrderGood.getInvoice_status()) {
                PurchaseInvoiceEnum invoiceEnum = PurchaseInvoiceEnum.NEW;
                newMemberPurchaseOrderGoods.put("invoice_status", invoiceEnum.id.toString());
            }
            //商品含税合计
            BigDecimal goodsPurchaseAmount = BigDecimalUtils.round(BigDecimalUtils.add(BigDecimalUtils.mul(BigDecimalUtils.isNull(memberPurchaseOrderGood.getPrice())
                    , BigDecimalUtils.isNull(memberPurchaseOrderGood.getNum())), BigDecimalUtils.isNull(memberPurchaseOrderGood.getFreight())), 2);
            //采购单含税总价
            purchaseAmount = BigDecimalUtils.add(purchaseAmount, goodsPurchaseAmount);
            //未税单价
            memberPurchaseOrderGood.setPre_price(BigDecimalUtils.div(BigDecimalUtils.isNull(memberPurchaseOrderGood.getPrice())
                    , BigDecimalUtils.isNull(memberPurchaseOrder.getInvoice_rate()).add(BigDecimal.ONE), 16));

            //商品未税合计
            BigDecimal goodsPrePurchaseAmount = BigDecimalUtils.round(BigDecimalUtils.add(BigDecimalUtils.mul(memberPurchaseOrderGood.getNum()
                    , BigDecimalUtils.isNull(newMemberPurchaseOrderGoods.get("pre_price"))), BigDecimalUtils.div(BigDecimalUtils.isNull(memberPurchaseOrderGood.getFreight())
                    , BigDecimalUtils.isNull(memberPurchaseOrder.getInvoice_rate()).add(BigDecimal.ONE), 2)), 2);

            //采购单未税合计
            prePurchaseAmount = BigDecimalUtils.add(prePurchaseAmount, goodsPrePurchaseAmount);
            newMemberPurchaseOrderGoods.put("amount", goodsPurchaseAmount);
            newMemberPurchaseOrderGoods.put("pretax_amount", goodsPrePurchaseAmount);
            newMemberPurchaseOrderGoods.put("refund_num", 0.00);
            //冗余采购员
            newMemberPurchaseOrderGoods.put("buyer", buyerName);
            newMemberPurchaseOrderGoods.put("vendor_name", vendorName);
            newMemberPurchaseOrderGoods.put("id", memberPurchaseOrderGood.getId());
            saveMemberPurchaseGoods.add(newMemberPurchaseOrderGoods);
        }
        memberPurchaseOrderMap.put("purchase_amount", purchaseAmount);
        memberPurchaseOrderMap.put("pre_purchase_amount", prePurchaseAmount);
        memberPurchaseOrderMap.put("member_purchase_order_status", MemberPurchaseOrderEnum.NEW.id.toString());
        memberPurchaseOrderMap.put("memberPurchaseOrderGoodsList", saveMemberPurchaseGoods);
        return memberPurchaseOrderMap;
    }

    /**
     * 修改采购订单
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.update
     *
     * @param mbp
     * @return
     * @throws RuntimeException
     */
    @Override
    public SingleResponse<BO> editPurchaseOrder(MemberPurchaseOrderDto mbp) throws RuntimeException {
        SingleResponse<BO> result = null;
        //修改采购订单
        //删除原有的采购订单商品
        //根据传过来的采购订单关联的订单商品save
        //原来的的采购订单
        List<MemberPurchaseOrderDto> oldmpos = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).selectField("*")
                .eq("id", mbp.getId()).queryForPOJOList(MemberPurchaseOrderDto.class);
        if(CollectionUtils.isEmpty(oldmpos)){
            throw new RuntimeException("转采订单不存在");
        }
        MemberPurchaseOrderDto oldmpo = oldmpos.get(0);

        //采购未税总计
        BigDecimal prePurchaseAmount = BigDecimalUtils.div(mbp.getPurchase_amount(), BigDecimalUtils.add(mbp.getInvoice_rate(), BigDecimal.ONE), 2);
        //毛利
        BigDecimal ml = BigDecimalUtils.mul(BigDecimalUtils.div(BigDecimalUtils.sub(mbp.getPre_sale_amount(), mbp.getPre_purchase_amount()), mbp.getPre_sale_amount()), new BigDecimal("100"));

        oldmpo.setTransfer_order_ids(mbp.getTransfer_order_ids());
        //采购订单修改
        if (mbp != null) {
            if (checkPurchaseOrder(mbp)) {
                oldmpo.setId(mbp.getId());
                //付款方式
                oldmpo.setPayment_id(mbp.getPayment_id());
                //发票税率
                oldmpo.setInvoice_rate(mbp.getInvoice_rate());
                //cloudID
                oldmpo.setCloud_order_ids(mbp.getCloud_order_ids());
                //淘宝账户
                oldmpo.setPay_account_id(mbp.getPay_account_id());
                //采购日期
                //  oldmpo.setTime(mbp.getTime());
                //需求日期
                oldmpo.setRequested_date(mbp.getRequested_date());
                //备注
                oldmpo.setMemo(mbp.getMemo());
                oldmpo.setMember_purchase_order_status(MemberPurchaseOrderEnum.NEW.id.toString());
                oldmpo.setInvoice_status(PurchaseInvoiceEnum.NEW.id.toString());
                //发票类型
                oldmpo.setInvoice_type(mbp.getInvoice_type());
                //销售总价含税
                oldmpo.setSale_amount(mbp.getSale_amount());
                //销售总价未税
                oldmpo.setPre_sale_amount(mbp.getPre_sale_amount());
                //采购总价含税
                oldmpo.setPurchase_amount(mbp.getPurchase_amount());
                //采购总价未税
                oldmpo.setPre_purchase_amount(mbp.getPre_purchase_amount());
                //未申请付款金额
                oldmpo.setNo_payment_amount(mbp.getPurchase_amount());
                oldmpo.setCustomer_name(StringUtils.repeatString(mbp.getCustomer_name(), ","));
                //供应商id
                oldmpo.setVendor_id(mbp.getVendor_id());
                //毛利率
                oldmpo.setGross_profit_margin(mbp.getGross_profit_margin());
//                BoServiceUtils.deleteBo(ModelConst.T_MEMBER_PURCHASE_ORDER, oldmpo.getId(), false);
                //添加采购商品
                oldmpo.setMemberPurchaseOrderGoods(mbp.getMemberPurchaseOrderGoods());
                Map<String, Object> memberPurchaseOrderMap = saveMemberPurchaseGoods(oldmpo);
                List<Map<String, Object>> memberPurchaseOrderGoodsMap = (ArrayList) memberPurchaseOrderMap.get("memberPurchaseOrderGoodsList");
                result = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderMap);
                BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, memberPurchaseOrderGoodsMap);
                if (!result.isSuccess()) {
                    throw new RuntimeException("修改失败");
                }
            }
        }
        return result;
    }

    /**
     * 验证采购订单及商品
     * cn/gomro/core/bizes/purchase/management/service/impl/TransferOrderService.checkTransOrder
     */
    private boolean checkTransOrder(TransferOrderDto transferOrder) throws RuntimeException {

        boolean checkOk = null != transferOrder && null != transferOrder.getMember_id() && null != transferOrder.getCloud_order_goods_id()
                && null != transferOrder.getTax_rate() && null != transferOrder.getTotal() && null != transferOrder.getAmount()
                && null != transferOrder.getReceiver() && null != transferOrder.getPhone() && null != transferOrder.getAddress();

        if (checkOk) {
            //校验转采商品
            Map<String, Object> param = new HashMap<>();
            param.put("transfer_order_id", transferOrder.getId());
            List<Map<String, Object>> transferOrderGoodsList = selectModelByMap(param, ModelConst.T_TRANSFER_ORDER_GOODS);
            if (!CollectionUtils.isEmpty(transferOrderGoodsList)) {
                for (Map<String, Object> transferOrderGoods : transferOrderGoodsList)
                    checkOk = null != transferOrderGoods.get("cloud_order_goods_id") && null != transferOrderGoods.get("vendor_id")
                            && null != transferOrderGoods.get("category") && null != transferOrderGoods.get("brand") && null != transferOrderGoods.get("name")
                            && null != transferOrderGoods.get("model") && null != transferOrderGoods.get("unit") && null != transferOrderGoods.get("amount") &&
                            null != transferOrderGoods.get("total");
            } else {

                throw new RuntimeException("操作失败:转采订单商品的必填项需要填写");
            }

        } else {
            throw new RuntimeException("操作失败:转采订单必填项需要填写");
        }

        return checkOk;
    }

    /**
     * 分配采购员
     *
     * @param transferOrderGoodsIds 转采商品id
     * cn/gomro/core/bizes/purchase/management/service/impl/TransferOrderService.updatePurchaseAgent
     * @return
     * @parem purchaseAgentId 采购员id
     */
    public boolean updatePurchaseAgent(List<String> transferOrderGoodsIds, String purchaseAgentId) throws RuntimeException {
        if (null == transferOrderGoodsIds) {
            throw new RuntimeException("订单商品ID为空");
        }
        if (null == purchaseAgentId) {
            throw new RuntimeException("采购员ID为空");
        }
        //根据供应商订单查询订单商品
        Map<String, Object> purchasingAgentMap = JdbcTemplateUtils.builder(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_PURCHASING_AGENT).selectField("name")
                .eq("id", purchaseAgentId).queryForMap();
        Integer i = JdbcTemplateUtils.builder(ModelConst.T_TRANSFER_ORDER_GOODS).putFieldAndVal("purchasing_agent_id", purchaseAgentId)
                .putFieldAndVal("purchase_agent_name", purchasingAgentMap.get("name")).in("id", transferOrderGoodsIds).update();
        return i >= 0 ? true : false;
    }

    /**
     * 返回待采以及标记已采购
     *
     * @param transferOrderGoodsIds
     * @param notPurchaseFlag
     * @param reason
     * @return
     * @throws RuntimeException
     */
    @Override
    public boolean tagPurchaseGoods(List<String> transferOrderGoodsIds, String notPurchaseFlag, String reason) throws RuntimeException {
        if (transferOrderGoodsIds.isEmpty()) {
            throw new RuntimeException("转采商品ID为空");
        }
        if (StringUtils.isBlank(notPurchaseFlag)) {
            throw new RuntimeException("是否再次采购为空");
        }
        //根据供应商订单查询订单商品
        String idInSql = transferOrderGoodsIds.stream().map(s -> "\'" + s + "\'").collect(Collectors.joining(", "));
        String reasonSql = "";
        if (!StringUtils.isBlank(reason)) {
            reasonSql = ",reason ='" + reason + "'";
        }
        String sql = "update " + getTableName(ModelConst.T_TRANSFER_ORDER_GOODS) + " set not_purchase =" + notPurchaseFlag + "" + reasonSql + " where id in (" + idInSql + ")";
        int i = jdbcTemplate.update(sql, new HashMap<>());
        return i >= 0 ? true : false;
    }

    /**
     * 采购订单审核通过
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.approvePurchaseOrder
     *
     * @param memberPurchaseOrderIds
     */
    @Override
    public SingleResponse<BO> approvePurchaseOrder(List<String> memberPurchaseOrderIds) {
        if (CollectionUtils.isEmpty(memberPurchaseOrderIds)) {
            throw new RuntimeException("会员采购订单ID集合必填");
        }
        List<Map<String, Object>> memberPurchaseOrders = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                .selectField("*").in("id", memberPurchaseOrderIds).queryForList();
        if (CollectionUtils.isEmpty(memberPurchaseOrders)) {
            throw new RuntimeException("采购订单不存在");
        }
//        List<Map<String, Object>> memberPurchaseOrderParams = new ArrayList<>();
        SingleResponse<BO> response = null;
        for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrders) {
            if (!memberPurchaseOrder.get("member_purchase_order_status").equals(MemberPurchaseOrderEnum.NEW.id.toString())) {
                throw new RuntimeException("只有新建状态的采购单才能审核");
            }
            Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
            memberPurchaseOrderParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.PAYMENT.id.toString());
            memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.RECEIVED.id.toString());
            memberPurchaseOrderParam.put("approve_time", new Date());
            memberPurchaseOrderParam.put("approve_user_name", RequestContext.getLoginRealName());
            memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
//            memberPurchaseOrderParams.add(memberPurchaseOrderParam);
            response = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);

            // 调用金蝶生成转采退货凭证
            //order_customer_id
            //注意 排序的问题
            Map<String, Object> param = new HashMap<>();
            param.put("member_purchase_order_id", memberPurchaseOrder.get("id"));
            String acceptTableName = JdbcTemplateUtils.getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS);
            StringBuilder sqlS = new StringBuilder("SELECT oa.* FROM ");
            sqlS.append(acceptTableName);
            sqlS.append(" AS oa WHERE oa.member_purchase_order_id IN (:member_purchase_order_id) ORDER BY oa.id ASC");

            //获取 客户订商品表 集合
            List<Map<String, Object>> memberPurchaseOrderGoodsList = JdbcTemplateUtils.queryForList(sqlS.toString(), param);

            List<KingDeeMemberPurchaseOrderGood> kingDeeMemberPurchaseOrderGoodList = new ArrayList<>();

            for (Map<String, Object> memberPurchaseOrderGoods : memberPurchaseOrderGoodsList) {

                KingDeeMemberPurchaseOrderGood kingDeeMemberPurchaseOrderGood = new KingDeeMemberPurchaseOrderGood();
                kingDeeMemberPurchaseOrderGood.setPretaxAmount(new BigDecimal(String.valueOf(memberPurchaseOrderGoods.get("pretax_amount"))));
                kingDeeMemberPurchaseOrderGoodList.add(kingDeeMemberPurchaseOrderGood);

            }

            Map<String, Object> memberPurchaseOrderMap = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).eq("id", memberPurchaseOrder.get("id")).selectField("*").queryForMap();

            String orgOrTransfer = "";
            try {
                orgOrTransfer = TransferFinanceUtil.getKingdeeOrgId(String.valueOf(memberPurchaseOrderMap.get("vendor_name")));
            } catch (Exception e) {
                log.error("获取 供应商名称 异常 ！！！");
                e.printStackTrace();
            }

            KingDeeMemberPurchaseOrder kingDeeMemberPurchaseOrder = KingDeeMemberPurchaseOrder.builder()
                    .poCode(String.valueOf(memberPurchaseOrderMap.get("po_code")))
                    .vendorId(orgOrTransfer)
                    .prePurchaseAmount(new BigDecimal(String.valueOf(memberPurchaseOrderMap.get("pre_purchase_amount"))))
                    .transferVendorName(String.valueOf(memberPurchaseOrderMap.get("vendor_name")))
                    .isRp(Boolean.valueOf(String.valueOf(memberPurchaseOrderMap.get("is_rp"))))
                    .kingDeeMemberPurchaseOrderGoods(kingDeeMemberPurchaseOrderGoodList)
                    .accountName(String.valueOf(memberPurchaseOrderMap.get("platform_name"))).build();

            TransferPurchaseVoucherService transferPurchaseVoucherService = new TransferPurchaseVoucherService();

            SingleResponse singleResponse = transferPurchaseVoucherService.purchaseReturnCertificate(kingDeeMemberPurchaseOrder);

        }
        return response;
    }

    /**
     * 采购订单审核驳回
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.disapprovePurchaseOrder
     */
    @Override
    public boolean disapprovePurchaseOrder(List<String> memberPurchaseOrderIds) throws RuntimeException {
        List<Map<String, Object>> memberPurchaseOrderParams = new ArrayList<>();
        List<Map<String, Object>> memberPurchaseOrders = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                .selectField("*").in("id", memberPurchaseOrderIds).queryForList();
        if (null == memberPurchaseOrders || memberPurchaseOrders.isEmpty())
            throw new RuntimeException("采购订单不存在！");
        for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrders) {
            if (!memberPurchaseOrder.get("member_purchase_order_status").equals(MemberPurchaseOrderEnum.NEW.id.toString())) {
                throw new RuntimeException("只有新建状态的采购单才能驳回");
            }
            List<Map<String, Object>> memberPurchaseOrderGoods = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS)
                    .selectField("*").in("member_purchase_order_id", memberPurchaseOrder.get("id")).queryForList();
            List<Map<String, Object>> transferOrderGoodsParams = new ArrayList<>();
            for (Map<String, Object> memberPurchaseOrderGood : memberPurchaseOrderGoods) {
                Map<String, Object> transferOrderGoods = selectModelById((String) memberPurchaseOrderGood.get("transfer_order_goods_id"), ModelConst.T_TRANSFER_ORDER_GOODS);
                if (null != transferOrderGoods) {
                    Map<String, Object> transferOrderGoodsParam = new HashMap<>();
                    //驳回的时候更新转采订单商品的已采购数量
                    transferOrderGoodsParam.put("quantity_purchased", BigDecimalUtils.sub(BigDecimalUtils.isNull(transferOrderGoods.get("quantity_purchased")), BigDecimalUtils.isNull(memberPurchaseOrderGood.get("num"))));
                    transferOrderGoodsParam.put("id", memberPurchaseOrderGood.get("id"));
                    transferOrderGoodsParams.add(transferOrderGoodsParam);
                }
            }
            //修改转采订单商品
            BoServiceUtils.updateMainBo(ModelConst.T_TRANSFER_ORDER_GOODS, transferOrderGoodsParams);
            Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
            memberPurchaseOrderParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.DISMISSED.id.toString());
            memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.DISMISSED.id.toString());
            memberPurchaseOrderParam.put("approve_user_name", RequestContext.getLoginRealName());
            memberPurchaseOrderParam.put("approve_time", new Date());
            memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
            memberPurchaseOrderParams.add(memberPurchaseOrderParam);
        }
        SingleResponse<BO> boList = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParams);
        return boList.isSuccess();
    }

    /**
     * 提交申请付款
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseFinanceService.save
     *
     * @return
     */
    @Override
    public SingleResponse<BO> savePurchaseRequestPayment(PurchaseRequestPaymentDto dto) {
        //校验采购付款单
        validatePurchaseRequestPayment(dto);
        if (null == dto.getPurchase_payment_status()) {
            dto.setPurchase_payment_status(PurchaseRequestEnum.NEW.id.toString());
        }
        if (null == dto.getApplicant_id()) {
            SelectorFormat applicant = getSelectorFormat();
            dto.setApplicant_id(applicant);
            dto.setApplicant_name(applicant.getName());
        }
        Map<String, Object> purchaseRequestPayment = BeanUtil.beanToMap(dto);
        List<Map<String, Object>> purchasePaymentDetail = savePurchasePaymentDetail(dto);
        SingleResponse<BO> response = BoServiceUtils.createBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, Collections.singletonList(purchaseRequestPayment));
        for (Map<String, Object> objectMap : purchasePaymentDetail) {
            objectMap.put("payment_id", response.getData().getBizObjectId());
        }
        BoServiceUtils.createBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchasePaymentDetail);
        return response;
    }

    /**
     * 保存采购付款明细
     */
    private List<Map<String, Object>> savePurchasePaymentDetail(PurchaseRequestPaymentDto purchaseRequestPaymentNew) throws RuntimeException {
        List<Map<String, Object>> savePurchasePaymentDetail = new ArrayList<>();
        for (PurchaseRequestPaymentDetailDto purchasePaymentDetail : purchaseRequestPaymentNew.getPaymentDetails()) {
            List<Map<String, Object>> memberPurchaseOrders = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).selectField("*")
                    .eq("id", purchasePaymentDetail.getMember_purchase_order_id()).queryForList();

            //根据采购单号查询出付款历史
            List<Map<String, Object>> purchaseRequestPaymentDetail = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL).selectField("*")
                    .in("payment_detail_status", Arrays.asList(PurchaseRequestEnum.PAYED.id.toString(), PurchaseRequestEnum.NEW.id.toString(), PurchaseRequestEnum.PAYMENT.id.toString()))
                    .eq("member_purchase_order_id", purchasePaymentDetail.getMember_purchase_order_id()).queryForList();

            if (null == memberPurchaseOrders) {
                throw new RuntimeException("采购单不存在");
            }
            if (null == purchasePaymentDetail.getPayment()) {
                throw new RuntimeException("付款金额不能为空！");
            }
            //循环采购订单
            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrders) {
                if (null != memberPurchaseOrder.get("no_more_payment")&&memberPurchaseOrder.get("no_more_payment").equals("1")) {
                    throw new RuntimeException("不再付款的采购单无法再次付款");
                }
                //付款总金额
                Double payAmountD = purchaseRequestPaymentDetail.stream().mapToDouble(s -> BigDecimalUtils.isNull(s.get("payment")).doubleValue()).sum();
                BigDecimal payAmount = BigDecimalUtils.isNull(payAmountD);

                //累加付款的金额
                BigDecimal newPurchaseAmount = BigDecimalUtils.add(payAmount, purchasePaymentDetail.getPayment());
                //判断是否为采购单，false:采购单,true:退货单
                if (null!=memberPurchaseOrder.get("is_rp")&&memberPurchaseOrder.get("is_rp").equals("0")) {
                    if (purchasePaymentDetail.getPayment().compareTo(BigDecimal.ZERO) < 1) {
                        throw new RuntimeException("付款金额不能小于或等于0");
                    }
                }
                if (BigDecimalUtils.isNull(memberPurchaseOrder.get("purchase_amount")).abs().compareTo(purchasePaymentDetail.getPayment().abs()) == -1) {
                    throw new RuntimeException("付款单:" + memberPurchaseOrder.get("po_code") + "本次付款金额不能大于采购金额！");
                }
                if (newPurchaseAmount.abs().compareTo(BigDecimalUtils.isNull(memberPurchaseOrder.get("purchase_amount")).abs()) == 1) {
                    throw new RuntimeException("采购单:" + memberPurchaseOrder.get("po_code") + "本次付款累加大于采购总金额,本次最多付款：" + (BigDecimalUtils.sub(BigDecimalUtils.isNull(memberPurchaseOrder.get("purchase_amount")), payAmount)));
                }
                //回写采购订单的未付款金额
                JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).putFieldAndVal("no_payment_amount", BigDecimalUtils.sub(BigDecimalUtils.isNull(memberPurchaseOrder.get("no_payment_amount")), purchasePaymentDetail.getPayment()))
                        .eq("id", memberPurchaseOrder.get("id")).update();
            }
            Map<String, Object> newPurchasePaymentDetail = new HashMap<>();
            newPurchasePaymentDetail.put("member_purchase_order_id", purchasePaymentDetail.getMember_purchase_order_id());
            newPurchasePaymentDetail.put("payment", purchasePaymentDetail.getPayment());
            newPurchasePaymentDetail.put("invoice_status", PurchaseInvoiceEnum.NEW.name());
            newPurchasePaymentDetail.put("pre_payment", purchasePaymentDetail.getPre_payment());
            newPurchasePaymentDetail.put("payment_detail_status", PurchaseRequestEnum.NEW.id);
            newPurchasePaymentDetail.put("buyer", purchasePaymentDetail.getBuyer());
            savePurchasePaymentDetail.add(newPurchasePaymentDetail);
        }
        return savePurchasePaymentDetail;
    }

    /**
     * 校验采购付款是否必填
     *
     * @param dto
     */
    private void validatePurchaseRequestPayment(PurchaseRequestPaymentDto dto) {
        if (null == dto) {
            throw new RuntimeException("采购付款不存在");
        }
        if (null == dto.getPurchase_amount()) {
            throw new RuntimeException("采购总金额不能为空");
        }
        if (null == dto.getPayment_amount()) {
            throw new RuntimeException("支付总金额不能为空");
        }
        if (null == dto.getSale_amount()) {
            throw new RuntimeException("销售总金额不能为空");
        }
        if (null == dto.getVendor_id()) {
            throw new RuntimeException("供应商ID不能为空");
        }
    }

    /**
     * 采购收票保存
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseFinanceService.savePurchaseInvoice
     *
     * @param purchaseInvoice
     * @return
     */
    @Override
    public SingleResponse<BO> submitPurchaseOrder(@NotNull PurchaseInvoiceDto purchaseInvoice) {
        List<PurchasePaymentInvoiceDto> p = purchaseInvoice.getPurchasePaymentInvoices();
        if (null == purchaseInvoice) {
            throw new RuntimeException("收票单不能为空!");
        }
        if (p.isEmpty()) {
            throw new RuntimeException("采购单明细不能为空！");
        }
        if (null == purchaseInvoice.getInvoice_amount()) {
            throw new RuntimeException("收票金额不能为空！");
        }
        //采购单的收票总金额相加 必须等于采购总金额
        Double m = p.stream().filter(t -> t.getInvoice_amount() != null).mapToDouble(t -> t.getInvoice_amount().doubleValue()).sum();
        BigDecimal invoicePriceSum = BigDecimalUtils.round(BigDecimal.valueOf(m), 2);
        if (purchaseInvoice.getPurchase_amount().compareTo(invoicePriceSum) != 0) {
            throw new RuntimeException("收票总金额必须与输入采购单收票金额一致");
        }
        //补差金额不能大于2元
        Double balanceAmountSum = purchaseInvoice.getPurchaseInvoiceDetails().stream().filter(t -> t.getBalance_amount() != null).mapToDouble(pt -> pt.getBalance_amount().doubleValue()).sum();
        if (Double.compare(Math.abs(balanceAmountSum), 2.0) > 0) {
            throw new RuntimeException("补差金额总计不能大于2元");
        }

        List<Map<String, Object>> savePurchaseInvoiceDetails = savePurchaseInvoiceDetail(purchaseInvoice);

        List<Map<String, Object>> itemizeEntityList = new ArrayList<>();
        BigDecimal prePurchaseAmount = BigDecimal.ZERO;

        for (PurchasePaymentInvoiceDto f : p) {
            //采购单未税合计 用于限制采购单未税合计=发票金额未税合计+补差金额合计
            Map<String, Object> memberPurchaseOrder = selectModelById(f.getPurchase_id(), ModelConst.T_MEMBER_PURCHASE_ORDER);
            prePurchaseAmount = BigDecimalUtils.add(BigDecimal.ZERO, BigDecimalUtils.isNull(memberPurchaseOrder.get("pre_purchase_amount")));

            if (null == f.getInvoice_amount()) {
                throw new RuntimeException("请输入正确收票金额！");
            }
            if (memberPurchaseOrder.get("is_rp").equals("1")) {
                if (f.getInvoice_amount().compareTo(BigDecimal.ZERO) > -1) {
                    throw new RuntimeException("退货单必须输入负数发票");
                }
            } else {
                if (f.getInvoice_amount().compareTo(BigDecimal.ZERO) < 1) {
                    throw new RuntimeException("请输入正确的收票金额！");
                }
            }

            if (f.getInvoice_amount().abs().compareTo(BigDecimalUtils.isNull(memberPurchaseOrder.get("purchase_amount")).abs()) == 1) {
                throw new RuntimeException("采购单:" + memberPurchaseOrder.get("po_code") + "收票金额大于采购总金额");
            }
            if ((BigDecimalUtils.add(BigDecimalUtils.isNull(memberPurchaseOrder.get("invoice_price")), f.getInvoice_amount())).abs().compareTo(BigDecimalUtils.isNull(memberPurchaseOrder.get("purchase_amount")).abs()) == 1) {
                throw new RuntimeException("采购单:" + memberPurchaseOrder.get("po_code") + "本次收票金额累加大于采购金额");
            }
            Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
            memberPurchaseOrderParam.put("invoice_price", BigDecimalUtils.add(f.getInvoice_amount(), BigDecimalUtils.round(BigDecimalUtils.isNull(memberPurchaseOrder.get("invoice_price")), 2)));
            memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.OrderReceived.id);
            memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
            BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);
            //保存采购流水 用于财务报表统计
            Map<String, Object> invoice = new HashMap<>();
            invoice.put("purchase_id", f.getPurchase_id());
            invoice.put("invoice_id", null);
            invoice.put("invoice_amount", f.getInvoice_amount());
            invoice.put("invoice_itemize_status", PurchaseInvoiceEnum.OrderReceived.id);
            invoice.put("pre_invoice_amount", BigDecimalUtils.div(f.getInvoice_amount(), BigDecimalUtils.add(BigDecimalUtils.div(purchaseInvoice.getInvoice_rate(), new BigDecimal("100")), BigDecimal.ONE), 2));
            itemizeEntityList.add(invoice);
        }

        //保存采购收票表和采购收票明细
        Map<String, Object> savePurchaseInvoice = new HashMap<>();
        savePurchaseInvoice.put("purchase_order_id", purchaseInvoice.getPurchase_order_id());
        savePurchaseInvoice.put("po_code", purchaseInvoice.getPo_code());
        savePurchaseInvoice.put("invoice_amount", purchaseInvoice.getInvoice_amount());
        savePurchaseInvoice.put("purchase_amount", purchaseInvoice.getPurchase_amount());
        savePurchaseInvoice.put("invoice_rate", BigDecimalUtils.round(purchaseInvoice.getInvoice_rate(), 2));
        savePurchaseInvoice.put("title", purchaseInvoice.getTitle());
        savePurchaseInvoice.put("purchase_invoice_status", PurchaseInvoiceEnum.OrderReceived.id);
        savePurchaseInvoice.put("invoice_type", purchaseInvoice.getInvoice_type());
        savePurchaseInvoice.put("pre_invoice_amount", purchaseInvoice.getPre_invoice_amount());
        SelectorFormat receiverId = getSelectorFormat();
        savePurchaseInvoice.put("receiver_id", receiverId);
        savePurchaseInvoice.put("applicant", receiverId.getName());
        savePurchaseInvoice.put("platform_name", purchaseInvoice.getPlatform_name());
        savePurchaseInvoice.put("pre_purchase_amount", purchaseInvoice.getPre_purchase_amount());
        //计算发票未税合计 用于判断发票未税合计+补差合计=采购单未税合计 否则无法录入发票
        double sum = savePurchaseInvoiceDetails.stream().filter(t -> t.get("pre_invoice_price") != null)
                .mapToDouble(t -> BigDecimalUtils.sub(BigDecimalUtils.isNull(t.get("pre_invoice_price")), BigDecimalUtils.isNull(t.get("balance_amount"))).doubleValue()).sum();
        BigDecimal sumBD = BigDecimalUtils.round(new BigDecimal(sum), 2);
        if (sumBD.compareTo(prePurchaseAmount) != 0) {
            throw new RuntimeException("采购单未税合计必须等于发票金额未税合计加补差合计！");
        }
        SingleResponse<BO> purchaseInvoiceResponse = BoServiceUtils.createBo(ModelConst.T_PURCHASE_INVOICE, Collections.singletonList(savePurchaseInvoice));
        BoServiceUtils.createBo(ModelConst.T_PURCHASE_INVOICE_DETAIL, savePurchaseInvoiceDetails);
        if (!purchaseInvoiceResponse.isSuccess()) {
            throw new RuntimeException("收票单保存失败");
        }

        //保存收票明细
        List<Map<String, Object>> invoiceItemizes = itemizeEntityList.stream().peek(e -> e.put("invoice_id", purchaseInvoiceResponse.getData().getBizObjectId())).collect(Collectors.toList());
        SingleResponse<BO> invoiceItemizeResponse = BoServiceUtils.createBo(ModelConst.T_INVOICE_ITEMIZE, invoiceItemizes);
        if (!invoiceItemizeResponse.isSuccess()) {
            throw new RuntimeException("收票流水流水保存失败");
        }
        return purchaseInvoiceResponse;
    }

    /**
     * 保存发票明细
     */
    private List<Map<String, Object>> savePurchaseInvoiceDetail(PurchaseInvoiceDto purchaseInvoice) throws RuntimeException {
        List<Map<String, Object>> savePurchaseInvoiceDetail = new ArrayList<>();
        for (PurchaseInvoiceDetailDto purchaseInvoiceDetail : purchaseInvoice.getPurchaseInvoiceDetails()) {
            if (StringUtils.isBlank(purchaseInvoiceDetail.getInvoice_number())) {
                throw new RuntimeException("发票号码不能为空！");
            }
            if (null == purchaseInvoiceDetail.getInvoice_price()) {
                throw new RuntimeException("发票金额(含)不能为空！");
            }
            if (null == purchaseInvoiceDetail.getInvoice_time()) {
                throw new RuntimeException("发票时间不能为空！");
            }
            if (null == purchaseInvoiceDetail.getPre_invoice_price()) {
                throw new RuntimeException("发票金额(未)不能为空！");
            }
            if (null == purchaseInvoiceDetail.getTax_amount()) {
                throw new RuntimeException("税额不能为空！");
            }
            if (!RegexUtils.check(RegexUtils.Type.IS_PRICE, String.valueOf(BigDecimalUtils.isNull(purchaseInvoiceDetail.getBalance_amount()).abs()))) {
                throw new RuntimeException("增补金额只能为小数点后两位");
            }
            //初始化时间
            String sql = "SELECT count(p.id) FROM "+getTableName(ModelConst.T_PURCHASE_INVOICE_DETAIL)+" p  left  join "+getTableName(ModelConst.T_PURCHASE_INVOICE)+" i  on i.id=p.purchase_invoice_id " +
                    "WHERE p.deleted=FALSE AND i.deleted=FALSE AND i.status in (1,2,4,7) " +
                    "and  p.invoice_number=" + purchaseInvoiceDetail.getInvoice_number() + "  and p.createdTime < now() ";
            Integer count = jdbcTemplate.queryForObject(sql, new HashMap<>(), Integer.class);
            if (count > 0) {
                throw new RuntimeException("发票号码：" + purchaseInvoiceDetail.getInvoice_number() + "已经收取，请录入其他发票号码。");
            }
            //发票未税金额
            BigDecimal preInvoicePrice = BigDecimalUtils.div(purchaseInvoiceDetail.getInvoice_price(), BigDecimalUtils.add(BigDecimalUtils.div(purchaseInvoice.getInvoice_rate(), new BigDecimal("100")), BigDecimal.ONE), 2);
            //税额
            BigDecimal taxAmount = BigDecimalUtils.sub(purchaseInvoiceDetail.getInvoice_price(), preInvoicePrice);
            // 税额由于需要手动调整，验证金额范围
            if (BigDecimalUtils.sub(purchaseInvoiceDetail.getTax_amount(), taxAmount).abs().compareTo(new BigDecimal("2")) == 1) {
                throw new RuntimeException("发票" + purchaseInvoiceDetail.getInvoice_number() + "税额调整范围不能大于2");
            }
            BigDecimal invoicePrice = BigDecimalUtils.sub(purchaseInvoiceDetail.getInvoice_price(), purchaseInvoiceDetail.getTax_amount()).abs();
            if (invoicePrice.compareTo(purchaseInvoiceDetail.getInvoice_price().abs()) == 1) {
                throw new RuntimeException("发票" + purchaseInvoiceDetail.getInvoice_number() + "未税金额不能大于含税金额！");
            }
            Map<String, Object> newPurchaseInvoiceDetail = new HashMap<>();
            newPurchaseInvoiceDetail.put("invoice_number", purchaseInvoiceDetail.getInvoice_number());
            newPurchaseInvoiceDetail.put("invoice_time", purchaseInvoiceDetail.getInvoice_time());
            newPurchaseInvoiceDetail.put("invoice_price", purchaseInvoiceDetail.getInvoice_price());
            newPurchaseInvoiceDetail.put("memo", purchaseInvoiceDetail.getMemo());
            newPurchaseInvoiceDetail.put("tax_amount", purchaseInvoiceDetail.getTax_amount());
            newPurchaseInvoiceDetail.put("balance_amount", purchaseInvoiceDetail.getBalance_amount());
            newPurchaseInvoiceDetail.put("pre_invoice_price", purchaseInvoiceDetail.getPre_invoice_price());
            newPurchaseInvoiceDetail.put("purchaseInvoice", purchaseInvoice);
            savePurchaseInvoiceDetail.add(newPurchaseInvoiceDetail);
        }
        return savePurchaseInvoiceDetail;
    }

    /**
     * 创建退货单
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.refund
     */
    @Override
    public SingleResponse<BO> createMemberPurchaseOrderRefund(MemberPurchaseOrderDto dto) {
        if (dto.getPurchase_amount().compareTo(BigDecimal.ZERO) == -1) {
            throw new RuntimeException("退货总金额不能小于等于0");
        }
        //查询旧的订单
        Map<String, Object> oldMemberPurchaseOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).selectField("*")
                .eq("id", dto.getId()).queryForMap();
        Map<String, Object> saveMemberPurchaseOrder = new HashMap<>();
        if (null == dto.getPo_code()) {
            saveMemberPurchaseOrder.put("po_code", "R" + oldMemberPurchaseOrder.get("po_code"));
        }else{
            saveMemberPurchaseOrder.put("po_code", "R" + dto.getPo_code());
        }
        if (null == dto.getNo_payment_amount()) {
            saveMemberPurchaseOrder.put("no_payment_amount", dto.getPurchase_amount().negate());
        }
        saveMemberPurchaseOrder.put("transfer_order_ids", oldMemberPurchaseOrder.get("transfer_order_ids"));
        saveMemberPurchaseOrder.put("payment_id", oldMemberPurchaseOrder.get("payment_id"));
        saveMemberPurchaseOrder.put("vendor_id", oldMemberPurchaseOrder.get("vendor_id"));
        saveMemberPurchaseOrder.put("invoice_rate", oldMemberPurchaseOrder.get("invoice_rate"));
        saveMemberPurchaseOrder.put("memo", oldMemberPurchaseOrder.get("memo"));
        saveMemberPurchaseOrder.put("refund_reason", dto.getRefund_reason());
        saveMemberPurchaseOrder.put("customer_name", oldMemberPurchaseOrder.get("customer_name"));
        saveMemberPurchaseOrder.put("invoice_type", oldMemberPurchaseOrder.get("invoice_type"));
        saveMemberPurchaseOrder.put("sale_amount", dto.getSale_amount().negate());
        saveMemberPurchaseOrder.put("pre_sale_amount", dto.getPre_sale_amount().negate());
        saveMemberPurchaseOrder.put("invoice_status", PurchaseInvoiceEnum.NEW.id.toString());
        saveMemberPurchaseOrder.put("member_purchase_order_status", MemberPurchaseOrderEnum.NEW.id.toString());
        saveMemberPurchaseOrder.put("gross_profit_margin", BigDecimalUtils.div(BigDecimalUtils.sub(dto.getPre_sale_amount(),
                dto.getPre_purchase_amount()), dto.getPre_sale_amount(), 2).negate());
        saveMemberPurchaseOrder.put("requested_date", oldMemberPurchaseOrder.get("requested_date"));
        saveMemberPurchaseOrder.put("invoice_price", BigDecimal.ZERO);
        saveMemberPurchaseOrder.put("is_rp", true);
        saveMemberPurchaseOrder.put("buyer", oldMemberPurchaseOrder.get("buyer"));
        saveMemberPurchaseOrder.put("buyer_id", oldMemberPurchaseOrder.get("buyer_id"));
        saveMemberPurchaseOrder.put("contract_or_sent", false);
        saveMemberPurchaseOrder.put("pay_account_id", oldMemberPurchaseOrder.get("pay_account_id"));
        saveMemberPurchaseOrder.put("cloud_order_ids", oldMemberPurchaseOrder.get("cloud_order_ids"));
        saveMemberPurchaseOrder.put("relation_purchase_id", oldMemberPurchaseOrder.get("id"));
        saveMemberPurchaseOrder.put("platform_name", oldMemberPurchaseOrder.get("platform_name"));
        saveMemberPurchaseOrder = refundMemberPurchaseGoods(saveMemberPurchaseOrder, dto.getMemberPurchaseOrderGoods());
        SingleResponse<BO> bo = BoServiceUtils.createBo(ModelConst.T_MEMBER_PURCHASE_ORDER, Collections.singletonList(saveMemberPurchaseOrder));
        return bo;
    }

    /**
     * 保存退货商品
     */
    private Map<String, Object> refundMemberPurchaseGoods(Map<String, Object> memberPurchaseOrder, List<MemberPurchaseOrderGoodsDto> memberPurchaseOrderGoods) throws RuntimeException {
        List<Map<String, Object>> saveMemberPurchaseGoods = new ArrayList<>();
        BigDecimal returnGoodsAmount = BigDecimal.ZERO;
        BigDecimal returnGoodsPreAmount = BigDecimal.ZERO;
        for (MemberPurchaseOrderGoodsDto m : memberPurchaseOrderGoods) {
            Map<String, Object> oldGoods = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS).selectField("*")
                    .eq("id", m.getId()).queryForMap();
            if (m.getNum().compareTo(BigDecimalUtils.isNull(oldGoods.get("num"))) == 1) {
                throw new RuntimeException("退货数量不能大于采购数量");
            }
            if (BigDecimalUtils.isNull(oldGoods.get("num")).compareTo(BigDecimalUtils.add(BigDecimalUtils.isNull(oldGoods.get("refund_num")), m.getNum())) == -1) {
                throw new RuntimeException("退货数量大于累加退货数量");
            }
            Map<String, Object> newGoods = new HashMap<>();
            newGoods.put("transfer_order_goods_id", oldGoods.get("transfer_order_goods_id"));
            newGoods.put("price", BigDecimalUtils.isNull(oldGoods.get("price")).negate());
            newGoods.put("pre_price", BigDecimalUtils.isNull(oldGoods.get("pre_price")).negate());
            newGoods.put("freight", oldGoods.get("freight"));
            newGoods.put("num", m.getNum());
            BigDecimal amount = BigDecimalUtils.round(BigDecimalUtils.mul(BigDecimalUtils.isNull(m.getNum()), BigDecimalUtils.isNull(oldGoods.get("price"))), 2).negate();
            returnGoodsAmount = BigDecimalUtils.add(amount, returnGoodsAmount);
            newGoods.put("amount", amount.negate());
            newGoods.put("gross_profit_rate", BigDecimalUtils.isNull(m.getGross_profit_rate()).negate());
            newGoods.put("delivery_time", oldGoods.get("delivery_time"));
            newGoods.put("invoice_status", PurchaseInvoiceEnum.NEW.id.toString());
            newGoods.put("member_purchase_goods_status", MemberPurchaseOrderGoodsEnum.NEW.id.toString());
            newGoods.put("memo", oldGoods.get("memo"));
            BigDecimal pretaxAmount = BigDecimalUtils.round(BigDecimalUtils.mul(BigDecimalUtils.isNull(m.getNum()), BigDecimalUtils.isNull(oldGoods.get("pre_price"))), 2).negate();
            returnGoodsPreAmount = BigDecimalUtils.add(pretaxAmount, returnGoodsPreAmount);
            newGoods.put("pretax_amount", pretaxAmount);
            newGoods.put("memberPurchaseOrder", memberPurchaseOrder);
            saveMemberPurchaseGoods.add(newGoods);
            //退货数量回写
            Map<String, Object> goodsParam = new HashMap<>();
            goodsParam.put("id", m.getId());
            goodsParam.put("refund_num", BigDecimalUtils.add(BigDecimalUtils.isNull(oldGoods.get("refund_num")), m.getNum()));
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, goodsParam);
            if (!response.isSuccess()) {
                throw new RuntimeException("商品退货数量回写失败");
            }
        }
        memberPurchaseOrder.put("purchase_amount", returnGoodsAmount);
        memberPurchaseOrder.put("pre_purchase_amount", returnGoodsPreAmount);
        memberPurchaseOrder.put("memberPurchaseOrderGoods", saveMemberPurchaseGoods);
        return memberPurchaseOrder;
    }

    /**
     * 付款单审核
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseFinanceService.approvePurchaseRequestPayment
     *
     * @param dto
     * @return
     */
    @Override
    public Boolean approvePurchaseRequestPayment(PurchaseRequestPaymentDto dto) {
        if (CollectionUtils.isEmpty(dto.getIds())) {
            throw new RuntimeException("付款单ID为空！");
        }
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", dto.getIds()).queryForList();
        if (null == purchaseRequestPayments || purchaseRequestPayments.isEmpty()) {
            throw new RuntimeException("付款单不存在！");
        }
        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {
            if (!purchaseRequestPayment.get("purchase_payment_status").equals(PurchaseRequestEnum.NEW.id.toString())) {
                throw new RuntimeException("只有新建状态的付款单才能审核");
            }
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").in("payment_id", purchaseRequestPayment.get("id")).queryForList();
            if (dto.getIs_pass()) {
                purchaseRequestPayment.put("purchase_payment_status", PurchaseRequestEnum.PAYMENT.id.toString());
                for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {
                    purchaseRequestPaymentDetail.put("payment_detail_status", PurchaseRequestEnum.PAYMENT.id.toString());
                    purchaseRequestPaymentDetail.put("pre_payment", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("pre_payment")), 2));
                    purchaseRequestPaymentDetail.put("payment", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("payment")), 2));
                    //此方法保存明细的状态
                }
            } else {
                purchaseRequestPayment.put("purchase_payment_status", PurchaseRequestEnum.DISMISSED.id.toString());
                for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {
                    purchaseRequestPaymentDetail.put("payment_detail_status", PurchaseRequestEnum.DISMISSED.id.toString());
                    purchaseRequestPaymentDetail.put("pre_payment", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("pre_payment")), 2));
                    purchaseRequestPaymentDetail.put("payment", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("payment")), 2));
                    //此方法保存明细的状态
                    //查询采购单未付款金额，回写，作废的时候 未付款金额=未付款金额+本次付款金额
                    Map<String, Object> memberPurchaseOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                            .selectField("*").in("member_purchase_order_id", purchaseRequestPaymentDetail.get("member_purchase_order_id")).queryForMap();
                    if (null != memberPurchaseOrder) {
                        Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                        memberPurchaseOrderParam.put("no_payment_amount", BigDecimalUtils.add(BigDecimalUtils.isNull(memberPurchaseOrder.get("no_payment_amount")), BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("payment"))));
                        memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
                        SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);
                        if (!response.isSuccess()) {
                            throw new RuntimeException("采购单未付款金额回写失败！");
                        }
                    }
                }
            }
            purchaseRequestPayment.put("approve_user_name", getSelectorFormat().getName());
            purchaseRequestPayment.put("approve_time", new Date());
            purchaseRequestPayment.put("approve_comments", dto.getApprove_comments());
            //字段格式化
            purchaseRequestPayment.put("pre_payment_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("pre_payment_amount")), 2));
            purchaseRequestPayment.put("pre_sale_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("pre_sale_amount")), 2));
            purchaseRequestPayment.put("payment_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("payment_amount")), 2));
            purchaseRequestPayment.put("pre_purchase_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("pre_purchase_amount")), 2));
            purchaseRequestPayment.put("purchase_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("purchase_amount")), 2));
            purchaseRequestPayment.put("sale_amount", BigDecimalUtils.round(BigDecimalUtils.isNull(purchaseRequestPayment.get("sale_amount")), 2));
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPayment);
            BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetails);
            if (!response.isSuccess()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 采购付款作废
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseFinanceService.abandonPayment
     */
    @Override
    public boolean abandonPayment(List<String> ids) throws RuntimeException {
        List<Map<String, Object>> purchaseRequestPayments = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT)
                .selectField("*").in("id", ids).queryForList();
        if (null == purchaseRequestPayments || purchaseRequestPayments.isEmpty()) {
            throw new RuntimeException("付款单不存在！");
        }
        for (Map<String, Object> purchaseRequestPayment : purchaseRequestPayments) {
            if (!purchaseRequestPayment.get("purchase_payment_status").equals(PurchaseRequestEnum.NEW.id.toString())) {
                throw new RuntimeException("只有新建状态的付款单才能作废");
            }
            List<Map<String, Object>> purchaseRequestPaymentDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                    .selectField("*").in("payment_id", purchaseRequestPayment.get("id")).queryForList();

            for (Map<String, Object> purchaseRequestPaymentDetail : purchaseRequestPaymentDetails) {
                purchaseRequestPaymentDetail.put("payment_detail_status", PurchaseRequestEnum.ABANDON.getId());
                //查询采购单未付款金额，回写，作废的时候 未付款金额=未付款金额+本次付款金额
                Map<String, Object> memberPurchaseOrder = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                        .selectField("*").in("member_purchase_order_id", purchaseRequestPaymentDetail.get("member_purchase_order_id")).queryForMap();
                if (null != memberPurchaseOrder) {
                    Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                    memberPurchaseOrderParam.put("no_payment_amount", BigDecimalUtils.add(BigDecimalUtils.isNull(memberPurchaseOrder.get("no_payment_amount")), BigDecimalUtils.isNull(purchaseRequestPaymentDetail.get("payment"))));
                    memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
                    SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParam);
                    if (!response.isSuccess()) {
                        throw new RuntimeException("采购单未付款金额回写失败！");
                    }
                }
            }
            purchaseRequestPayment.put("purchase_payment_status", PurchaseRequestEnum.ABANDON.id.toString());
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT, purchaseRequestPayment);
            BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL, purchaseRequestPaymentDetails);
            if (!response.isSuccess()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 转采修改发票明细
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseFinanceService.updatePurchaseInvoice
     *
     * @param dto
     */
    @Override
    public SingleResponse<BO> updatePurchaseInvoice(PurchaseInvoiceDto dto) {

        if (CollectionUtils.isEmpty(dto.getPurchaseInvoiceDetails())) {
            throw new RuntimeException("收票单明细不能为空");
        }
        Map<String, Object> purchaseInvoice = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE).selectField("*").eq("id", dto.getId()).queryForMap();

        if (null == purchaseInvoice) {
            throw new RuntimeException("收票单不能为空");
        }

        if (!purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.FinanceDismissed.id.toString())) {
            throw new RuntimeException("状态为财务已退票的才能修改");
        }

        List<Map<String, Object>> purchaseInvoiceDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL)
                .selectField("*").eq("purchase_invoice_id", dto.getId()).queryForList();

        for (Map<String, Object> detail : purchaseInvoiceDetails) {
            dto.getPurchaseInvoiceDetails().forEach(e -> {
                if (e.getId().equals(detail.get("id"))) {
                    detail.put("invoice_number", e.getInvoice_number());
                    detail.put("invoice_time", e.getInvoice_time());
                }
            });
        }
        purchaseInvoice.put("purchase_invoice_status", PurchaseInvoiceEnum.OrderReceived.id.toString());
        //修改采购单明细
        List<String> orderIds = StringUtils.stringToListString((String) purchaseInvoice.get("purchase_order_id"), ",");

        List<Map<String, Object>> memberPurchaseOrderEntities = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                .selectField("*").in("id", orderIds).queryForList();
        List<Map<String, Object>> memberPurchaseOrderParams = new ArrayList<>();
        for (Map<String, Object> order : memberPurchaseOrderEntities) {
            Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
            memberPurchaseOrderParam.put("id", order.get("id"));
            memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.OrderReceived.id.toString());
            memberPurchaseOrderParams.add(memberPurchaseOrderParam);
        }
        BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParams);
        return BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoice);
    }

    /**
     * 取消收票或 财务确认收票
     */
    @Override
    public boolean invoiceCancelOrConfirm(List<String> idList, String type, String addFinancialInvoiceTime) throws RuntimeException {
        if (CollectionUtils.isEmpty(idList) || StringUtils.isBlank(type)) {
            return false;
        }
        idList = idList.stream().distinct().collect(Collectors.toList());
        List<Map<String, Object>> purchaseInvoiceEntities = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE)
                .selectField("*").in("id", idList).queryForList();
        if (CollectionUtils.isEmpty(purchaseInvoiceEntities)) {
            throw new RuntimeException("收票单不存在");
        }
        List<Map<String, Object>> purchaseInvoiceParams = new ArrayList<>();
        for (Map<String, Object> purchaseInvoice : purchaseInvoiceEntities) {
            Map<String, Object> purchaseInvoiceParam = new HashMap<>();
            String invoiceIds = (String) purchaseInvoice.get("id");
            List<String> orderIds = StringUtils.stringToListString((String) purchaseInvoice.get("purchase_order_id"), ",");
            List<Map<String, Object>> memberPurchaseOrderEntities = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                    .selectField("*").in("id", orderIds).queryForList();
            if (CollectionUtils.isEmpty(memberPurchaseOrderEntities)) {
                throw new RuntimeException("采购单不存在");
            }
            List<Map<String, Object>> invoiceItemizeEntities = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                    .selectField("*").in("invoice_id", invoiceIds).queryForList();
            if (CollectionUtils.isEmpty(invoiceItemizeEntities)) {
                throw new RuntimeException("采购收票流水查询失败！");
            }
            if (!purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.RECEIVED.id.toString()) &&
                    !purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.SENT.id.toString()) &&
                    !purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.CONFIRM.id.toString()) &&
                    !purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.FinanceDismissed.id.toString()) &&
                    !purchaseInvoice.get("purchase_invoice_status").equals(PurchaseInvoiceEnum.OrderReceived.id.toString())) {
                throw new RuntimeException("收票单状态不正确");
            }
            List<Map<String, Object>> memberPurchaseOrderParams = new ArrayList<>();
            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrderEntities) {
                Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                Map<String, Object> invoiceItemize = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                        .selectField("*").eq("invoice_id", purchaseInvoice.get("id")).eq("purchase_id", memberPurchaseOrder.get("id")).queryForMap();

                if (!memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.RECEIVED.id.toString())
                        && !memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.PARTIAL.id.toString())
                        && !memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.CONFIRM.id.toString())
                        && !memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.SENT.id.toString())
                        && !memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.FinanceDismissed.id.toString())
                        && !memberPurchaseOrder.get("member_purchase_order_status").equals(PurchaseInvoiceEnum.OrderReceived.id.toString())) {
                    throw new RuntimeException("采购单收票状态不正确");
                }
                if (type.equals("1")) {
                    //业务取消,判断收票金额跟采购单的收票金额是否一致，
                    purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.CANCEL.id.toString());
                    if (BigDecimalUtils.sub(BigDecimalUtils.isNull(memberPurchaseOrder.get("invoice_price")), BigDecimalUtils.isNull(invoiceItemize.get("invoice_amount"))).compareTo(BigDecimal.ZERO) == 0) {
                        memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.RECEIVED.id.toString());

                    } else if (BigDecimalUtils.sub(BigDecimalUtils.isNull(memberPurchaseOrder.get("invoice_price")), BigDecimalUtils.isNull(invoiceItemize.get("invoice_amount"))).compareTo(BigDecimal.ZERO) == 1) {
                        memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.PARTIAL.id.toString());
                    }
                    memberPurchaseOrderParam.put("invoice_price", BigDecimalUtils.sub(BigDecimalUtils.isNull(memberPurchaseOrder.get("invoice_price")), BigDecimalUtils.isNull(invoiceItemize.get("invoice_amount"))));
                } else if (type.equals("2")) {
                    //财务确认 采购订单状态修改
                    memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.CONFIRM.id.toString());
                    //发票申请单状态修改
                    purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.CONFIRM.id.toString());
                    purchaseInvoiceParam.put("financial_confirmer", getSelectorFormat());
                    purchaseInvoiceParam.put("financial_confirm_name", getSelectorFormat().getName());
                    purchaseInvoiceParam.put("financial_confirm_time", addFinancialInvoiceTime);
                } else if (type.equals("3")) {
                    //财务取消 采购单状态修改为财务已收票
                    memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.SENT.id.toString());
                    purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.SENT.id.toString());
                    purchaseInvoiceParam.put("financial_confirmer", null);
                    purchaseInvoiceParam.put("financial_confirm_name", null);
                    purchaseInvoiceParam.put("financial_confirm_time", null);
                } else if (type.equals("4")) {
                    //业务已提交财务，修改状态为财务已收票
                    purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.SENT.id.toString());
                    memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.SENT.id.toString());
                } else if (type.equals("5")) {
                    //财务驳回收票单
                    purchaseInvoiceParam.put("purchase_invoice_status", PurchaseInvoiceEnum.FinanceDismissed.id.toString());
                    memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.FinanceDismissed.id.toString());
                }
                memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
                memberPurchaseOrderParam.put("invoice_price", BigDecimalUtils.isNull(memberPurchaseOrderParam.get("invoice_price")).setScale(2, RoundingMode.HALF_UP));
                memberPurchaseOrderParams.add(memberPurchaseOrderParam);
                purchaseInvoiceParam.put("id", purchaseInvoice.get("id"));
                purchaseInvoiceParams.add(purchaseInvoiceParam);
            }
            //修改会员采购订单表数据
            SingleResponse<BO> memberRes = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER, memberPurchaseOrderParams);
            if (!memberRes.isSuccess()) {
                throw new RuntimeException("采购单回写失败");
            }
            List<Map<String, Object>> invoiceItemizeParams = new ArrayList<>();
            for (Map<String, Object> invoiceItemize : invoiceItemizeEntities) {
                Map<String, Object> invoiceItemizeParam = new HashMap<>();
                if (type.equals("1")) {
                    //业务取消
                    invoiceItemizeParam.put("invoice_itemize_status", PurchaseInvoiceEnum.CANCEL.id.toString());
                } else if (type.equals("2")) {
                    //财务确认
                    invoiceItemizeParam.put("financial_confirmation_time", addFinancialInvoiceTime);
                    invoiceItemizeParam.put("invoice_itemize_status", PurchaseInvoiceEnum.CONFIRM.id.toString());
                } else if (type.equals("3")) {
                    //财务取消
                    invoiceItemizeParam.put("financial_confirmation_time", null);
                    invoiceItemizeParam.put("invoice_itemize_status", PurchaseInvoiceEnum.RECEIVED.id.toString());
                }
                invoiceItemizeParams.add(invoiceItemizeParam);
            }
            SingleResponse<BO> response = BoServiceUtils.updateMainBo(ModelConst.T_PURCHASE_INVOICE, purchaseInvoiceParams);
            if (!response.isSuccess()) {
                throw new RuntimeException("收票单取消失败");
            }
            SingleResponse<BO> invoiceRes = BoServiceUtils.updateMainBo(ModelConst.T_INVOICE_ITEMIZE, invoiceItemizeParams);
            if (!invoiceRes.isSuccess()) {
                throw new RuntimeException("收票单流水回写失败！");
            }
        }
        try {
            invoiceConfirmReceipt(type, purchaseInvoiceEntities);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 确认或取消收票，生成凭证
     *
     * @param type
     * @param purchaseInvoiceEntities
     */
    public void invoiceConfirmReceipt(String type, List<Map<String, Object>> purchaseInvoiceEntities) {
        //确认收票生成凭证
        if (type.equals("2")) {
            String companyName = "";
            String vendorOrderId = "";
            SelectorFormat vendorId;
            List<KingDeePurchaseReceipt> receiptList = new ArrayList<>();

            for (Map<String, Object> pur : purchaseInvoiceEntities) {
                List<String> purchaseOrderIds = StringUtils.stringToListString((String) pur.get("purchase_order_id"), ",");
                List<Map<String, Object>> one = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER).selectField("*")
                        .in("id", purchaseOrderIds).queryForList();

                vendorId = (SelectorFormat) one.get(0).get("vendor_id");
                Set<String> vendorOrderIdByCustomerOrderId = null;
                for (Map<String, Object> t : one) {
                    List<String> cloudOrderIdList = StringUtils.stringToListString((String) t.get("cloud_order_ids"), ",");
                    List<String> vendorOrderIds = JdbcTemplateUtils.builder(ModelConst.T_ORDER_VENDOR).selectField("id")
                            .in("order_customer_id", cloudOrderIdList).queryForList(String.class);
                    vendorOrderIdByCustomerOrderId = new HashSet<>(vendorOrderIds);
                }
                vendorOrderId = org.apache.commons.lang3.StringUtils.join(vendorOrderIdByCustomerOrderId, ",");

                Map<String, BigDecimal> poDetail = new HashMap<>();
                //淘宝跟京东收票单独生成明细分录
                if (vendorId.equals(16) || vendorId.equals(124)) {
                    List<Map<String, Object>> invoiceItemizeEntities = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE).selectField("*")
                            .in("id", pur.get("id")).queryForList();
                    //流水
                    if (null != invoiceItemizeEntities && invoiceItemizeEntities.size() > 1) {
                        for (Map<String, Object> invoiceItemize : invoiceItemizeEntities) {
                            poDetail.put((String) invoiceItemize.get("po_code"), BigDecimalUtils.isNull(invoiceItemize.get("invoice_amount")));
                        }
                    }
                }

                List<Map<String, Object>> purchaseInvoiceDetails = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_INVOICE_DETAIL).selectField("*")
                        .in("purchase_invoice_id", pur.get("id")).queryForList();
                List<KingDeePurchaseReceiptDetail> detailList = new ArrayList<>();
                for (Map<String, Object> details : purchaseInvoiceDetails) {
                    KingDeePurchaseReceiptDetail detail = new KingDeePurchaseReceiptDetail();
                    List<String> poCodes = Arrays.asList(details.get("po_code").toString().split(",")).stream().map(s -> s.trim()).collect(Collectors.toList());
                    detail.setPoCode(null == poCodes.get(0) ? "" : poCodes.get(0));
                    detail.setInvoiceNumber((String) details.get("invoice_number"));
                    detail.setInvoicePrice(BigDecimalUtils.isNull(details.get("invoice_price")));
                    detail.setTaxAmount(BigDecimalUtils.isNull(details.get("tax_amount")));
                    detail.setPreInvoicePrice(BigDecimalUtils.isNull(details.get("pre_invoice_price")));
                    detail.setBalanceAmount(BigDecimalUtils.isNull(details.get("balance_amount")));
                    detail.setVendorOrderId(vendorOrderId);
                    detailList.add(detail);
                }
                //供应商名称
                companyName = pur.get("title").toString().trim();
                String orgOrTransfer = "";
                try {
                    orgOrTransfer = this.getOrgOrTransfer(companyName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //集合赋值
                KingDeePurchaseReceipt receipt = new KingDeePurchaseReceipt();
                receipt.setId((String) pur.get("id"));
                receipt.setCompanyName(companyName);
                receipt.setVendorOrgId(orgOrTransfer);
                receipt.setInvoiceRate(BigDecimalUtils.isNull(pur.get("invoice_rate")));
                receipt.setInvoiceAmount(BigDecimalUtils.isNull(pur.get("invoice_amount")));
                //调整为取采购单未税金额 -- > 改为发票·未税金额
                receipt.setPreInvoiceAmount(BigDecimalUtils.isNull(pur.get("pre_invoice_amount")));
                // 订单未税金额
                receipt.setPreOrderAmount(BigDecimalUtils.isNull(pur.get("pre_purchase_amount")));
                receipt.setInvoiceType((String) pur.get("invoice_type"));
                receipt.setFinancialConfirmTime((String) pur.get("financial_confirm_time"));
                receipt.setPurchaseInvoiceDetailList(detailList);
                receipt.setPoDetail(poDetail);
                receipt.setAccountName((String) pur.get("platform_name"));
                receiptList.add(receipt);
            }


            try {
//                kingDeeApi.receiptCredentialGeneration(receiptList);
            } catch (Exception e) {
                log.error("转采收票生成凭证异常{}\n{}", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e));
            }
        }
        //取消收票生成凭证
        if (type.equals("3")) {
            try {
//                List<KingDeeCancelPayment> kingDeeCancelPayments = purchaseInvoiceEntities.stream().map(t -> new KingDeeCancelPayment(t.getId().longValue(), t.getPlatformName())).collect(Collectors.toList());
//                kingDeeApi.purchaseCancelBillingDeleteVoucher(kingDeeCancelPayments);
            } catch (Exception e) {
                log.error("转采取消收票生成凭证异常{}\n{}", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e));
            }
        }
    }

    public String getOrgOrTransfer(String orgName) {
        String orgId = "";
        String pmVendor = null;
        String trVendor = null;
        if (StringUtils.isNotBlank(orgName)) {
//            Organization data = organizationApi.getByName(orgName.trim()).getData();
//            if (data != null) {
//                pmVendor = data.get("id").toString();
//            }
            trVendor = JdbcTemplateUtils.builder(ModelConst.T_TRANSFER_VENDOR).selectField("id")
                    .eq("company_name", orgName.trim()).queryForObject(String.class);
        }
        // Pm有转采没有 或者 Pm有转采也有
        if (pmVendor != null) {
            orgId = pmVendor;
            return orgId;
            // Pm没有 转采有
        } else if (trVendor != null) {
            orgId = "Z" + trVendor;
        }
        return orgId;
    }

    /**
     * 采购单作废
     * cn/gomro/core/bizes/purchase/management/service/impl/PurchaseOrderService.purchaseReturn
     *
     * @param ids
     * @return
     */
    @Override
    public boolean purchaseReturn(List<String> ids, Integer type) {
        if (CollectionUtils.isEmpty(ids) || null == type) {
            return false;
        }
        boolean result = false;
        List<Map<String, Object>> memberPurchaseOrders = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                .selectField("*").in("id", ids).queryForList();
        List<Map<String, Object>> paymentDetail = JdbcTemplateUtils.builder(ModelConst.T_PURCHASE_REQUEST_PAYMENT_DETAIL)
                .selectField("*").in("member_purchase_order_id", ids)
                .in("payment_detail_status", Arrays.asList(PurchaseRequestEnum.NEW, PurchaseRequestEnum.PAYMENT, PurchaseRequestEnum.PAYED)).queryForList();
        List<Map<String, Object>> invoiceItemize = JdbcTemplateUtils.builder(ModelConst.T_INVOICE_ITEMIZE)
                .selectField("*").in("purchase_id", ids)
                .in("invoice_itemize_status", Arrays.asList("1", "2", "4")).queryForList();
        if (null != paymentDetail && paymentDetail.size() > 0) {
            throw new RuntimeException("存在未回退的付款单,请先驳回!");
        }
        if (null != invoiceItemize && invoiceItemize.size() > 0) {
            throw new RuntimeException("存在未回退的收票单，请先回退！");
        }
        if (null == memberPurchaseOrders) {
            throw new RuntimeException("采购订单不存在！");
        } else {
            for (Map<String, Object> memberPurchaseOrder : memberPurchaseOrders) {
                List<Map<String, Object>> memberPurchaseOrderGoodsList = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS)
                        .selectField("*").in("member_purchase_order_id", memberPurchaseOrder.get("id")).queryForList();
                Map<String, Object> memberPurchaseOrderParam = new HashMap<>();
                for (Map<String, Object> memberPurchaseOrderGoods : memberPurchaseOrderGoodsList) {
                    if (type == 1) {
                        Map<String, Object> s = JdbcTemplateUtils.builder(ModelConst.T_TRANSFER_ORDER_GOODS)
                                .selectField("*").in("id", memberPurchaseOrderGoods.get("transfer_order_goods_id")).queryForMap();
                        if (null != s) {
                            //作废的时候更新转采订单商品的已采购数量
                            Map<String, Object> transferOrderGoodsParam = new HashMap<>();
                            transferOrderGoodsParam.put("quantity_purchased", BigDecimalUtils.sub(BigDecimalUtils.isNull(s.get("quantity_purchased")), BigDecimalUtils.isNull(memberPurchaseOrderGoods.get("num"))));
                            transferOrderGoodsParam.put("id", s.get("id"));
                            BoServiceUtils.updateMainBo(ModelConst.T_TRANSFER_ORDER_GOODS, transferOrderGoodsParam);
                        }
                        //如果作废的是采购单，由于作废需要回写原采购商品里的退货数量，需要查询原采购商品，重新回写数量
                        if ((Boolean) memberPurchaseOrder.get("is_rp")) {
                            Map<String, Object> refundPurchase = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER)
                                    .selectField("*").in("relation_purchase_id", memberPurchaseOrder.get("id")).queryForMap();
                            List<Map<String, Object>> refundMemberPurchaseOrderGoods = JdbcTemplateUtils.builder(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS)
                                    .selectField("*").in("member_purchase_order_id", memberPurchaseOrder.get("id")).queryForList();
                            List<Map<String, Object>> collect = refundMemberPurchaseOrderGoods.stream()
                                    .filter(t -> t.get("transfer_order_goods_id").equals(memberPurchaseOrderGoods.get("transfer_order_goods_id")))
                                    .peek(t -> t.put("refund_num", (BigDecimalUtils.sub(BigDecimalUtils.isNull(t.get("refund_num")), BigDecimalUtils.isNull(memberPurchaseOrderGoods.get("num")))))).collect(Collectors.toList());
                            BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, collect);
//                            refundPurchase.setMemberPurchaseOrderGoodsList(collect);
                        }
                        //业务作废
                        memberPurchaseOrderParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.CANCEL.id.toString());
                        memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.ABANDON.id.toString());
                    } else if (type == 2) {
                        //业务驳回未新建新建
                        memberPurchaseOrderParam.put("invoice_status", PurchaseInvoiceEnum.NEW.id.toString());
                        memberPurchaseOrderParam.put("member_purchase_order_status", MemberPurchaseOrderEnum.NEW.id.toString());
                        memberPurchaseOrderParam.put("approve_tim", null);
                        memberPurchaseOrderParam.put("approve_user_name", null);
                    }
                }
                memberPurchaseOrderParam.put("id", memberPurchaseOrder.get("id"));
                SingleResponse<BO> bo = BoServiceUtils.updateMainBo(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, memberPurchaseOrderParam);
                result = bo.isSuccess();
            }

        }
        return result;
    }

    /**
     * 调用创建金税单
     */
    /*private void creatGoldenTax(Map<String, Object> resaleInvoiceEntity) {
        List<Map<String, Object>> resaleInvoiceDetails = JdbcTemplateUtils.builder(ModelConst.T_TRANSFER_ORDER)
                .selectField("*").eq("resale_invoice_id", resaleInvoiceEntity.get("id")).queryForList();
        Map<String, List<Map<String, Object>>> invoiceDetails = resaleInvoiceDetails.stream().collect(Collectors.groupingBy(t->(String) t.get("goods_id")));
        List<Long> ids = sequenceApi.batchId(invoiceDetails.size()).getData();
        List<Map<String, Object>> goldenTaxDetailList = new ArrayList<>();

        AtomicInteger index = new AtomicInteger();
        invoiceDetails.forEach((key, values) -> {
            BigDecimal num = BigDecimal.ZERO, price = BigDecimal.ZERO, total = BigDecimal.ZERO, taxRate = BigDecimal.ZERO, tax = BigDecimal.ZERO;
            String goldenTax = "", name = "", modelSpec = "", unit = "";

            for (Map<String, Object> invoiceDetail : values) {
                price = BigDecimalUtils.add(price, BigDecimalUtils.isNull(invoiceDetail.get("price")));
                total = BigDecimalUtils.add(total, BigDecimalUtils.isNull(invoiceDetail.get("total")));
                tax = BigDecimalUtils.add(tax, BigDecimalUtils.isNull(invoiceDetail.get("tax")));
                goldenTax = (String) invoiceDetail.get("golden_tax");
                taxRate = BigDecimalUtils.isNull(invoiceDetail.get("tax_rate"));
                num = BigDecimalUtils.isNull(invoiceDetail.get("quantity"));
                name = (String) invoiceDetail.get("name");
                modelSpec = (String) invoiceDetail.get("model_spec");
                unit = (String) invoiceDetail.get("unit");
            }
            goldenTaxDetailList.add(new GoldenTaxDetail(ids.get(index.get()), name, modelSpec, unit, num, price, total, taxRate, tax, goldenTax));
            index.getAndIncrement();
        });

        GoldenTax goldenTax = new GoldenTax(apply.getGoldenTaxId(), apply.getPurchaseName(), apply.getPurchaseNumber(),
                apply.getPurchaseAddress() + " " + apply.getPurchasePhone(), apply.getPurchaseBank() + " " + apply.getPurchaseAccount(),
                apply.getApplyMemberName(), apply.getApplyMemberId().longValue(), apply.getMemo(), apply.getPriceAmount(), goldenTaxDetailList);
        goldenTaxApi.create(Collections.singletonList(goldenTax));
    }*/

    /**
     * 通过采购订单ID查询转采订单商品数据
     * @param dto
     * @return
     */
    @Override
    public SingleResponse purchaseGoodsFindByPurchase(MemberPurchaseOrderDto dto) {
        if(StringUtils.isBlank(dto.getId())){
            return SingleResponse.buildFailure("-1", "采购订单ID必填");
        }
        String mpoTableName = getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER);
        String mpgTableName = getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS);
        String sql = "select mpg.* from "+mpoTableName+" mpo " +
                "INNER JOIN "+mpgTableName+" mpg on mpg.member_purchase_order_id = mpo.id " +
                "WHERE mpo.id =:id and mpo.deleted = false and mpg.deleted = false";
        Map<String, Object> param = new HashMap<>();
        param.put("id", dto.getId());
        return SingleResponse.of(JdbcTemplateUtils.queryForList(sql, param));
    }

    /**
     * 根据云平台订单商品号,查询转采供应商和RP采购单号，供应商，退款金额
     * @param orderGoodsId
     * @return
     */
    @Override
    public List<PurchaseOrderReturnDto> getPurchaseReturnInfo(String orderGoodsId) {
        String sql = " SELECT " +
                " SUM( G.amount ) as amount," +
                " SUM( G.num ) as num," +
                " group_concat( DISTINCT tv.company_name , ',' )  as vendorName , " +
                " group_concat( DISTINCT M.po_code , ',' )  as rpCode , " +
                " group_concat( DISTINCT M.refund_reason , ',' )  as rpMemo ," +
                " group_concat( DISTINCT M.createdTime, ',' )  as rpTime " +
                " FROM " +
                " "+getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS)+" " +
                " AS G LEFT JOIN "+getTableName(AppConst.ZHUANCAI,ModelConst.T_MEMBER_PURCHASE_ORDER)+" AS M ON M.ID = G.member_purchase_order_id " +
                " LEFT JOIN "+getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER_GOODS)+" AS T ON T.ID = G.transfer_order_goods_id " +
                " LEFT JOIN "+getTableName(AppConst.ZHUANCAI,ModelConst.T_TRANSFER_ORDER)+" AS o ON o.ID = T.transfer_order_id " +
                " Left join  "+getTableName(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_TRANSFER_VENDOR)+" as tv on tv.id=M.vendor_id " +
                " WHERE " +
                " G.deleted = 0 " +
                " AND o.order_type IS NULL " +
                " AND M.deleted = FALSE " +
                " AND M.is_rp = TRUE " +
                " AND M.member_purchase_order_status IN ( 2, 3, 4 ) " +
                " AND T.cloud_order_goods_id = ";
        if (null != orderGoodsId) {
            sql += orderGoodsId;
        }

        sql += " GROUP BY G.transfer_order_goods_id ";
        return JdbcTemplateUtils.queryForPOJOList(sql, new HashMap<>(), ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, PurchaseOrderReturnDto.class);
    }

    /**
     * 获取应用表名(可获取其他应用表名)
     *
     * @param appCode
     * @param schemaCode
     * @return
     */
    public String getTableName(String appCode, String schemaCode) {
        if (StringUtils.isBlank(appCode)) {
            return getTableName(schemaCode);
        }
        return String.format("%s.i_%s_%s", appCode.toLowerCase(), appCode.toLowerCase(), schemaCode.toLowerCase());
    }

}
